/**
 *  2013-6-3   上午5:38:06
 *  Created By niexiaoqiang
 */

package com.xiaoqiang.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

import android.os.Environment;

/**
 * 日志记录器
 */
public class Logger {

	//日志文件所在路径
    private static String logPath = Environment.getExternalStorageDirectory()
    		+File.separator+"mtw"+File.separator+"mtw_v2_c.log";
    private Object obj;
    //日志级别
    private LogType logtype=LogType.debug;
    //是否打开控制台
    public Logger(Object obj)
    {
        this.obj = obj;
    }
    public void info(String msg)
    {
        if (logtype == LogType.error)
        {
            return;
        }
        else
        {
            WriteLog("info",msg);
        }
    }
    public void error(String msg)
    {
        WriteLog("error",msg);
    }
    public void error(Exception e)
    {
    	StringBuffer sb=new StringBuffer();
    	sb.append(e.toString()+"\n");
		StackTraceElement[] fs=e.getStackTrace();
		for (StackTraceElement a : fs) {
			sb.append(a.toString()+"\n");
		}
        WriteLog("error",sb.toString());
    }
    public void debug(String msg)
    {
        if (logtype == LogType.info || logtype == LogType.error)
        {
            return;
        }
        else
        {
            WriteLog("debug",msg);
        }
    }

    private synchronized void WriteLog(String loglevel,String msg)
    {
		try {
			FileWriter fw = new FileWriter(new File(logPath),true);
			new Date();
			String allmsg =new Date().toGMTString() +"#"+ loglevel + "#"+obj.toString()
	         		+ "#" +  msg;
	    	fw.write(allmsg+"\n");
	    	fw.flush();
			fw.close();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
    }
}
/// <summary>
/// 日志类型
/// </summary>
enum LogType
{
  info,  //堆栈跟踪信息
  debug,//警告信息
  error,  //错误信息应该包含对象名、发生错误点所在的方法名称、具体错误信息
}
